// 等待视频播放器加载完成
function waitForVideoPlayer() {
  return new Promise((resolve) => {
    // 设置超时，避免无限等待
    const maxWaitTime = 30000; // 30秒
    const startTime = Date.now();

    const checkInterval = setInterval(() => {
      // 如果等待时间超过最大值，则停止等待
      if (Date.now() - startTime > maxWaitTime) {
        clearInterval(checkInterval);
        resolve(null);
        return;
      }

      const videoPlayer = document.querySelector(
        ".bpx-player-video-wrap video"
      );
      const speedMenu = document.querySelector(
        ".bpx-player-ctrl-playbackrate-menu"
      );

      if (videoPlayer && speedMenu) {
        clearInterval(checkInterval);
        resolve({ videoPlayer, speedMenu });
      }
    }, 1000);
  });
}

// 隐藏B站主页上的广告拦截提示
function hideAdblockTips() {
  // 创建一个样式元素
  const style = document.createElement("style");
  style.textContent = `
    /* 隐藏广告拦截提示 */
    .adblock-tips {
      display: none !important;
    }
  `;
  document.head.appendChild(style);

  // 检查并移除广告拦截提示
  const checkAndRemove = () => {
    const adblockTips = document.querySelector(".adblock-tips");
    if (adblockTips) {
      adblockTips.remove();
      console.log("B站视频倍速增强插件：已移除广告拦截提示");
    }
  };

  // 在DOM加载完成后执行一次
  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", checkAndRemove);
  } else {
    checkAndRemove();
  }

  // 创建MutationObserver监听DOM变化
  const observer = new MutationObserver((mutations) => {
    for (const mutation of mutations) {
      if (mutation.type === "childList" && mutation.addedNodes.length > 0) {
        // 检查是否添加了广告拦截提示
        const hasAdblockTips = Array.from(mutation.addedNodes).some((node) => {
          if (node.nodeType === Node.ELEMENT_NODE) {
            return node.classList && node.classList.contains("adblock-tips");
          }
          return false;
        });

        if (hasAdblockTips) {
          checkAndRemove();
          break;
        }
      }
    }
  });

  // 监听body的变化
  observer.observe(document.body, {
    childList: true,
    subtree: true,
  });
}

// 创建新的倍速选项
function createSpeedOption(speed) {
  const speedItem = document.createElement("li");
  speedItem.className = "bpx-player-ctrl-playbackrate-menu-item";
  speedItem.textContent = `${speed}x`;
  speedItem.setAttribute("data-value", speed);

  return speedItem;
}

// 从存储中获取用户设置
async function getUserSettings() {
  return new Promise((resolve) => {
    chrome.storage.sync.get(
      {
        // 默认设置
        customSpeeds: [1.35, 1.45, 1.75],
        lastUsedSpeed: null,
        enableKeyboardShortcuts: true,
      },
      (items) => {
        resolve(items);
      }
    );
  });
}

// 保存最后使用的倍速
function saveLastUsedSpeed(speed) {
  chrome.storage.sync.set({ lastUsedSpeed: speed });
}

// 添加自定义倍速输入框
function addCustomSpeedInput(speedMenu) {
  // 检查是否已经添加过
  if (speedMenu.querySelector(".bpx-player-ctrl-playbackrate-custom")) {
    return;
  }

  // 创建一个分隔线
  const separator = document.createElement("div");
  separator.className = "bpx-player-ctrl-playbackrate-menu-separator";
  separator.style.height = "1px";
  separator.style.background = "rgba(255, 255, 255, 0.1)";
  separator.style.margin = "5px 10px";

  // 创建自定义倍速容器
  const customSpeedContainer = document.createElement("div");
  customSpeedContainer.className = "bpx-player-ctrl-playbackrate-custom";
  customSpeedContainer.style.padding = "5px 10px";
  customSpeedContainer.style.display = "flex";
  customSpeedContainer.style.alignItems = "center";

  // 创建输入框
  const input = document.createElement("input");
  input.type = "number";
  input.min = "0.1";
  input.max = "5";
  input.step = "0.05";
  input.placeholder = "自定义倍速";
  input.style.width = "70px";
  input.style.height = "24px";
  input.style.background = "rgba(255, 255, 255, 0.1)";
  input.style.border = "none";
  input.style.borderRadius = "4px";
  input.style.color = "white";
  input.style.padding = "0 5px";

  // 创建应用按钮
  const applyBtn = document.createElement("button");
  applyBtn.textContent = "应用";
  applyBtn.style.marginLeft = "5px";
  applyBtn.style.height = "24px";
  applyBtn.style.background = "#00a1d6";
  applyBtn.style.border = "none";
  applyBtn.style.borderRadius = "4px";
  applyBtn.style.color = "white";
  applyBtn.style.padding = "0 8px";
  applyBtn.style.cursor = "pointer";

  // 应用按钮点击事件
  applyBtn.addEventListener("click", () => {
    const customSpeed = parseFloat(input.value);
    if (customSpeed && customSpeed >= 0.1 && customSpeed <= 5) {
      const videoPlayer = document.querySelector(
        ".bpx-player-video-wrap video"
      );
      if (videoPlayer) {
        videoPlayer.playbackRate = customSpeed;

        // 更新当前选中的倍速显示
        const speedDisplay = document.querySelector(
          ".bpx-player-ctrl-playbackrate-result"
        );
        if (speedDisplay) {
          speedDisplay.textContent = `${customSpeed}x`;
        }

        // 保存最后使用的倍速
        saveLastUsedSpeed(customSpeed);

        // 关闭倍速菜单
        const speedBtn = document.querySelector(
          ".bpx-player-ctrl-playbackrate"
        );
        if (speedBtn) {
          speedBtn.classList.remove("bpx-state-show");
        }
      }
    }
  });

  // 添加到容器
  customSpeedContainer.appendChild(input);
  customSpeedContainer.appendChild(applyBtn);

  // 添加到菜单
  speedMenu.appendChild(separator);
  speedMenu.appendChild(customSpeedContainer);
}

// 添加新的倍速选项到菜单
async function addCustomSpeeds(speedMenu) {
  // 如果菜单为空或不是预期的元素，则退出
  if (
    !speedMenu ||
    !speedMenu.classList.contains("bpx-player-ctrl-playbackrate-menu")
  ) {
    return;
  }

  // 获取用户设置
  const settings = await getUserSettings();

  // 要添加的自定义倍速
  const customSpeeds = settings.customSpeeds;

  // 获取所有现有的倍速选项
  const existingItems = Array.from(
    speedMenu.querySelectorAll(".bpx-player-ctrl-playbackrate-menu-item")
  );

  // 检查是否已经添加过自定义倍速
  const hasCustomSpeeds = existingItems.some((item) => {
    const speed = parseFloat(item.getAttribute("data-value"));
    return customSpeeds.includes(speed);
  });

  // 如果已经添加过，则不再重复添加
  if (hasCustomSpeeds) {
    return;
  }

  // 创建并添加新的倍速选项
  customSpeeds.forEach((speed) => {
    // 检查这个倍速是否已经存在
    const exists = existingItems.some(
      (item) => parseFloat(item.getAttribute("data-value")) === speed
    );

    if (!exists) {
      const newSpeedItem = createSpeedOption(speed);

      // 找到合适的位置插入新选项，保持倍速从大到小排序
      let inserted = false;
      for (let i = 0; i < existingItems.length - 1; i++) {
        const currentSpeed = parseFloat(
          existingItems[i].getAttribute("data-value")
        );
        const nextSpeed = parseFloat(
          existingItems[i + 1].getAttribute("data-value")
        );

        if (speed < currentSpeed && speed > nextSpeed) {
          speedMenu.insertBefore(newSpeedItem, existingItems[i + 1]);
          existingItems.splice(i + 1, 0, newSpeedItem);
          inserted = true;
          break;
        }
      }

      // 如果没有找到合适的位置，添加到末尾
      if (!inserted) {
        speedMenu.appendChild(newSpeedItem);
        existingItems.push(newSpeedItem);
      }
    }
  });

  // 为所有倍速选项添加点击事件
  setupSpeedClickEvents(speedMenu);

  // 添加自定义倍速输入框
  addCustomSpeedInput(speedMenu);

  // 应用上次使用的倍速
  if (settings.lastUsedSpeed) {
    const videoPlayer = document.querySelector(".bpx-player-video-wrap video");
    if (videoPlayer) {
      videoPlayer.playbackRate = settings.lastUsedSpeed;

      // 更新当前选中的倍速显示
      const speedDisplay = document.querySelector(
        ".bpx-player-ctrl-playbackrate-result"
      );
      if (speedDisplay) {
        speedDisplay.textContent = `${settings.lastUsedSpeed}x`;
      }

      // 更新选中状态
      existingItems.forEach((item) => {
        const itemSpeed = parseFloat(item.getAttribute("data-value"));
        if (itemSpeed === settings.lastUsedSpeed) {
          item.classList.add("bpx-player-ctrl-playbackrate-menu-item-active");
        }
      });
    }
  }
}

// 设置倍速选项的点击事件
function setupSpeedClickEvents(speedMenu) {
  // 获取所有倍速选项
  const items = speedMenu.querySelectorAll(
    ".bpx-player-ctrl-playbackrate-menu-item"
  );

  // 如果没有找到倍速选项，则退出
  if (items.length === 0) {
    return;
  }

  // 获取视频播放器
  const videoPlayer = document.querySelector(".bpx-player-video-wrap video");
  if (!videoPlayer) {
    return;
  }

  // 为每个倍速选项添加点击事件
  items.forEach((item) => {
    // 检查是否已经添加过点击事件
    if (item.getAttribute("data-has-click-event") === "true") {
      return;
    }

    // 标记已添加点击事件
    item.setAttribute("data-has-click-event", "true");

    // 添加点击事件
    item.addEventListener("click", (event) => {
      // 阻止事件冒泡，避免触发B站原有的点击事件
      event.stopPropagation();

      const speed = parseFloat(item.getAttribute("data-value"));

      // 设置视频播放速度
      if (videoPlayer) {
        videoPlayer.playbackRate = speed;
      }

      // 更新当前选中的倍速显示
      const speedDisplay = document.querySelector(
        ".bpx-player-ctrl-playbackrate-result"
      );
      if (speedDisplay) {
        speedDisplay.textContent = `${speed}x`;
      }

      // 更新选中状态
      items.forEach((i) =>
        i.classList.remove("bpx-player-ctrl-playbackrate-menu-item-active")
      );
      item.classList.add("bpx-player-ctrl-playbackrate-menu-item-active");

      // 保存最后使用的倍速
      saveLastUsedSpeed(speed);

      // 关闭倍速菜单
      const speedBtn = document.querySelector(".bpx-player-ctrl-playbackrate");
      if (speedBtn) {
        speedBtn.classList.remove("bpx-state-show");
      }
    });
  });
}

// 设置键盘快捷键
async function setupKeyboardShortcuts() {
  const settings = await getUserSettings();

  // 如果未启用键盘快捷键，则返回
  if (!settings.enableKeyboardShortcuts) {
    return;
  }

  // 检查是否已经设置过键盘快捷键
  if (document.body.getAttribute("data-speed-shortcuts-added") === "true") {
    return;
  }

  // 标记已添加快捷键
  document.body.setAttribute("data-speed-shortcuts-added", "true");

  // 添加键盘事件监听器
  document.addEventListener("keydown", handleKeyboardShortcut);
}

// 处理键盘快捷键
function handleKeyboardShortcut(event) {
  // 确保不在输入框中触发快捷键
  if (event.target.tagName === "INPUT" || event.target.tagName === "TEXTAREA") {
    return;
  }

  const videoPlayer = document.querySelector(".bpx-player-video-wrap video");
  if (!videoPlayer) {
    return;
  }

  let newSpeed = videoPlayer.playbackRate;
  let handled = false;

  // 使用 + 和 - 键调整倍速
  if (event.key === "+" || event.key === "=") {
    // 增加 0.1 倍速
    newSpeed = Math.min(5, Math.round((newSpeed + 0.1) * 100) / 100);
    handled = true;
  } else if (event.key === "-" || event.key === "_") {
    // 减少 0.1 倍速
    newSpeed = Math.max(0.1, Math.round((newSpeed - 0.1) * 100) / 100);
    handled = true;
  } else if (event.key === "0") {
    // 重置为 1.0 倍速
    newSpeed = 1.0;
    handled = true;
  } else if (event.key >= "1" && event.key <= "9") {
    // 数字键 1-9 对应 0.5x 到 2.5x 倍速
    const speedMap = {
      1: 0.5,
      2: 0.75,
      3: 1.0,
      4: 1.25,
      5: 1.5,
      6: 1.75,
      7: 2.0,
      8: 2.25,
      9: 2.5,
    };
    newSpeed = speedMap[event.key];
    handled = true;
  }

  // 如果处理了快捷键，则应用新的倍速
  if (handled) {
    // 阻止默认行为，避免与B站原有快捷键冲突
    event.preventDefault();

    // 应用新的倍速
    videoPlayer.playbackRate = newSpeed;

    // 更新当前选中的倍速显示
    const speedDisplay = document.querySelector(
      ".bpx-player-ctrl-playbackrate-result"
    );
    if (speedDisplay) {
      speedDisplay.textContent = `${newSpeed}x`;
    }

    // 保存最后使用的倍速
    saveLastUsedSpeed(newSpeed);

    // 显示倍速提示
    showSpeedNotification(newSpeed);
  }
}

// 显示倍速变化提示
function showSpeedNotification(speed) {
  // 检查是否已存在提示元素
  let notification = document.querySelector(
    ".bpx-player-custom-speed-notification"
  );

  if (!notification) {
    // 创建提示元素
    notification = document.createElement("div");
    notification.className = "bpx-player-custom-speed-notification";
    notification.style.position = "absolute";
    notification.style.top = "70px";
    notification.style.left = "50%";
    notification.style.transform = "translateX(-50%)";
    notification.style.background = "rgba(0, 0, 0, 0.7)";
    notification.style.color = "white";
    notification.style.padding = "8px 16px";
    notification.style.borderRadius = "4px";
    notification.style.fontSize = "14px";
    notification.style.zIndex = "100";
    notification.style.opacity = "0";
    notification.style.transition = "opacity 0.3s";

    // 添加到播放器
    const playerContainer = document.querySelector(".bpx-player-container");
    if (playerContainer) {
      playerContainer.appendChild(notification);
    }
  }

  // 更新提示内容
  notification.textContent = `播放速度: ${speed}x`;

  // 显示提示
  notification.style.opacity = "1";

  // 2秒后隐藏
  setTimeout(() => {
    notification.style.opacity = "0";
  }, 2000);
}

// 优化后的MutationObserver，只监听特定元素
function setupMutationObserver() {
  // 检查是否已经设置过MutationObserver
  if (window._speedEnhancerObserverSet) {
    return;
  }

  // 标记已设置MutationObserver
  window._speedEnhancerObserverSet = true;

  // 创建一个防抖函数，避免频繁处理
  const debounce = (fn, delay) => {
    let timer = null;
    return function () {
      if (timer) {
        clearTimeout(timer);
      }
      timer = setTimeout(() => {
        fn.apply(this, arguments);
        timer = null;
      }, delay);
    };
  };

  // 防抖处理函数
  const debouncedHandler = debounce(async () => {
    const videoPlayer = document.querySelector(".bpx-player-video-wrap video");
    const speedMenu = document.querySelector(
      ".bpx-player-ctrl-playbackrate-menu"
    );

    if (videoPlayer && speedMenu) {
      await addCustomSpeeds(speedMenu);
    }
  }, 500);

  // 创建MutationObserver
  const observer = new MutationObserver((mutations) => {
    // 检查是否有相关元素的变化
    for (const mutation of mutations) {
      if (mutation.type === "childList") {
        // 检查是否添加了新的播放器控制元素
        const hasPlayerControls = Array.from(mutation.addedNodes).some(
          (node) => {
            if (node.nodeType === Node.ELEMENT_NODE) {
              return (
                node.classList &&
                (node.classList.contains("bpx-player-control-wrap") ||
                  node.classList.contains("bpx-player-ctrl-playbackrate") ||
                  node.classList.contains("bpx-player-ctrl-playbackrate-menu"))
              );
            }
            return false;
          }
        );

        if (hasPlayerControls) {
          debouncedHandler();
          break;
        }
      }
    }
  });

  // 只监听播放器容器的变化，减少不必要的监听
  const playerContainer = document.querySelector(".bpx-player-container");
  if (playerContainer) {
    observer.observe(playerContainer, {
      childList: true,
      subtree: true,
      attributes: false,
      characterData: false,
    });
  } else {
    // 如果没有找到播放器容器，则监听body的直接子元素变化
    observer.observe(document.body, {
      childList: true,
      subtree: false,
      attributes: false,
      characterData: false,
    });
  }
}

// 清理函数，用于在页面卸载时清理资源
function cleanup() {
  // 移除键盘事件监听器
  document.removeEventListener("keydown", handleKeyboardShortcut);

  // 移除MutationObserver标记
  delete window._speedEnhancerObserverSet;

  // 移除body上的标记
  document.body.removeAttribute("data-speed-shortcuts-added");
}

// 处理来自弹出窗口的消息
function handleMessage(message, sender, sendResponse) {
  if (message.type === "settingsChanged") {
    // 更新设置
    if (message.settings.enableKeyboardShortcuts !== undefined) {
      if (message.settings.enableKeyboardShortcuts) {
        // 启用键盘快捷键
        setupKeyboardShortcuts();
      } else {
        // 禁用键盘快捷键
        document.removeEventListener("keydown", handleKeyboardShortcut);
        document.body.removeAttribute("data-speed-shortcuts-added");
      }
    }

    // 如果自定义倍速列表已更改，则刷新倍速菜单
    if (message.settings.customSpeeds !== undefined) {
      const speedMenu = document.querySelector(
        ".bpx-player-ctrl-playbackrate-menu"
      );
      if (speedMenu) {
        // 移除所有自定义倍速选项
        const items = speedMenu.querySelectorAll(
          ".bpx-player-ctrl-playbackrate-menu-item"
        );
        items.forEach((item) => {
          const speed = parseFloat(item.getAttribute("data-value"));
          if ([1.35, 1.45, 1.75].includes(speed)) {
            item.remove();
          }
        });

        // 重新添加自定义倍速选项
        addCustomSpeeds(speedMenu);
      }
    }

    // 响应消息
    sendResponse({ success: true });
  }
}

// 注册消息监听器
chrome.runtime.onMessage.addListener(handleMessage);

// 主函数
async function main() {
  try {
    // 注册清理函数
    window.addEventListener("unload", cleanup);

    // 隐藏B站主页上的广告拦截提示（在所有页面上执行）
    hideAdblockTips();

    // 等待视频播放器加载
    const result = await waitForVideoPlayer();

    // 如果没有找到视频播放器，则退出视频相关功能的设置
    if (!result) {
      console.log(
        "B站视频倍速增强插件：未找到视频播放器，仅执行广告拦截提示隐藏功能"
      );
      return;
    }

    const { speedMenu } = result;

    // 添加自定义倍速选项
    await addCustomSpeeds(speedMenu);

    // 设置键盘快捷键
    setupKeyboardShortcuts();

    // 设置变化监听器
    setupMutationObserver();

    console.log("B站视频倍速增强插件已加载");
  } catch (error) {
    console.error("B站视频倍速增强插件加载失败:", error);
  }
}

// 启动插件
main();
